package com.shiwaixiangcun.monitor.service.impl;

import com.rabbit.spring.data.domain.ext.Status;
import com.rabbit.spring.data.search.SearchOperator;
import com.rabbit.spring.data.search.Searchable;
import com.shiwaixiangcun.core.exceptions.MonkeyException;
import com.shiwaixiangcun.core.plugin.service.BaseTreeableServiceImpl;
import com.shiwaixiangcun.core.utils.MonkeyUtils;
import com.shiwaixiangcun.monitor.domain.WorkOrderCategory;
import com.shiwaixiangcun.monitor.enums.CategoryType;
import com.shiwaixiangcun.monitor.repository.WorkOrderCategoryRepository;
import com.shiwaixiangcun.monitor.service.WorkOrderCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Administrator on 2017-11-23.
 */
@Service
@Transactional
public class WorkOrderCategoryServiceImpl extends BaseTreeableServiceImpl<WorkOrderCategory, Long> implements WorkOrderCategoryService {

    @Autowired
    private WorkOrderCategoryRepository repository;

    @Override
    public void addWorkOrderCategory(String name, Long parentId) {
        Searchable searchable = Searchable.newSearchable();
        searchable.addSearchFilter("name", SearchOperator.eq, name);
        searchable.addSearchFilter("deleted", SearchOperator.eq, false);
        List<WorkOrderCategory> content = repository.findAll(searchable).getContent();
        if (MonkeyUtils.isNotEmpty(content)) {
            throw new MonkeyException("该名字已经被使用");
        }
        WorkOrderCategory parent = repository.findOne(parentId);
        WorkOrderCategory childCategory = new WorkOrderCategory();
        childCategory.setName(name);
        childCategory.setDeleted(false);
        childCategory.setType(CategoryType.Two_Level);
        if (parent.isRoot()) {
            childCategory.setType(CategoryType.One_Level);
        }
        appendChild(parent, childCategory);
    }

    @Override
    public void removeWorkOrderCategory(Long id) {
        WorkOrderCategory category = repository.findOne(id);
        if (MonkeyUtils.isNotEmpty(category)) {
            if (CategoryType.Top_Level.equals(category.getType())) {
                throw new MonkeyException("不能删除顶级分类");
            }
            List<WorkOrderCategory> children = findChildByParent(id, false);
            if (!children.isEmpty()) {
                throw new MonkeyException("当前分类包含子分类不能删除");
            }
        }
        repository.delete(id);
        category.setStatus(Status.DISABLE);
        repository.save(category);
    }

    @Override
    public WorkOrderCategory findByParentId(long l) {
        return repository.findByParentId(l);
    }
}
